const fs = require('fs')
const AliImg = require('ali-img')

const config = {
    accessKeyId: 'LTAIQDgUIXICt3BF',
    accessKeySecret: 'T5VeDf9NvkJqbhRI7fc0blF52nXO2F',
    region: 'oss-cn-shenzhen',
    bucket: 'wxlai'
  }


const img = new AliImg(config)

function resize(url,w,h){
    return new Promise(function(resolve,reject){
        const dest = url.replace('.jpg',`_${w}x${h}.jpg`).replace('http://oss.wxlai.com/','')
        img(url)
        .resize(w, h,{mode:'fill'})
        .save(dest,function(err){
          if(err){
            reject(err)
          }else{
            resolve('http://oss.wxlai.com/' + dest)
          }
        })
    })
}

Parse.Cloud.define('convertImage', async (req, res) => {
    try{
        const { url,type } = req.params
        const map = {
            club:[{w:120,h:120},{w:200,h:200}],
            resource:[{w:120,h:120},{w:200,h:200}],
            head:[{w:120,h:120}],
            qrcode:[{w:200,h:200}]
        }
        const list = map[type]
        const result=[]
        for(let i=0;i<list.length;i++){
            const info = list[i]
            const u = await resize(url,info.w,info.h)
            result.push(u)
        }
        res.success({info:list,urls:result})

    }catch(e){
        res.error(e)
    }

})